package com.zhouxiaoge.反射;

import java.lang.reflect.Constructor;

/**
 * @author 周小哥  gqzmy@163.com 2023/3/5 20:28
 */

public class ReflectConstructorsDemo {
    public static void main(String[] args) throws Exception {
        Class<?> aClass = Class.forName("com.zhouxiaoge.反射.Student");

        System.out.println("================================所有的公有构造方法================================");
        Constructor<?>[] constructors = aClass.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }

        System.out.println("================================所有的构造方法(私有、受保护、共有)================================");
        Constructor<?>[] declaredConstructors = aClass.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }
        System.out.println("================================获取公有无参构造方法================================");
        Constructor<?> constructor = aClass.getConstructor();
        System.out.println(constructor);

        System.out.println("================================获取私有构造方法，并调用================================");
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(char.class);
        System.out.println(declaredConstructor);
        declaredConstructor.setAccessible(true); // 暴力访问，忽略访问修饰符
        Object men = declaredConstructor.newInstance('男');
        System.out.println(men);
    }
}
